package task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by lizhenyu on 2019/9/14
 * description
 */
public class CallableTask {
    final static int taskNum = 3;

    public static void main(String[] args) {
        List<Future> futures = new ArrayList<>();
        // 开启线程池
        ExecutorService executor = Executors.newFixedThreadPool(taskNum);
        for(int i = 0; i < taskNum; i++) {
            Callable<Integer> seller = new CallableTickerSeller(i + 1);
            Future future = executor.submit(seller);
            futures.add(future);
        }
        try {
            for (Future future : futures) {
                // future.get() 方法具有阻塞性，直到获取Callable的返回值，主线程才继续执行
                System.out.println("主线程返回：" + future.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭线程池
        executor.shutdown();
    }
}

class CallableTickerSeller implements Callable<Integer> {
    private int taskId;

    CallableTickerSeller(int id) {
        this.taskId = id;
    }

    @Override
    public Integer call() throws Exception {
        int num = 10;
        try {
            while (num > 0) {
                System.out.println("窗口 " + taskId + " 还有 " + num + " 张票");
                num--;
                Thread.sleep(1000);
            }
            System.out.println("窗口 " + taskId + " 票已卖完");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return taskId;
    }

}